import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:go_router/go_router.dart';
import '../models/question.dart';
import '../services/database_service.dart';
import '../utils/word_import_export_util.dart';
import '../widgets/math_formula_widget.dart';
import 'dart:developer' as developer;
import 'dart:io';
import 'add_edit_question_screen.dart';
import 'question_import_export_screen.dart';


class QuestionListScreen extends StatefulWidget {
  final String questionType;
  
  const QuestionListScreen({super.key, required this.questionType});

  @override
  State<QuestionListScreen> createState() => _QuestionListScreenState();
}

class _QuestionListScreenState extends State<QuestionListScreen> {  
  final DatabaseService _databaseService = DatabaseService();
  List<Question> _questions = [];
  List<Question> _filteredQuestions = []; // 筛选后的题目列表
  bool _isLoading = true;
  String? _errorMessage;
  
  // 搜索相关
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';
  
  // 筛选相关
  String? _selectedCategory;
  String? _selectedKeyPoint;
  List<String> _categories = [];
  List<String> _keyPoints = [];
  
  // 多选相关
  bool _isMultiSelectMode = false;
  Set<int> _selectedQuestionIds = {}; // 存储选中的题目ID
  
  @override
  void initState() {
    super.initState();
    _loadQuestions();
    _loadCategories();
    _loadKeyPoints();
    
    // 添加搜索监听
    _searchController.addListener(_onSearchChanged);
  }
  
  @override
  void dispose() {
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();
    super.dispose();
  }
  
  // 加载分类列表
  Future<void> _loadCategories() async {
    try {
      // 获取所有题目
      final allQuestions = await _databaseService.questionRepository.getAllQuestions();
      
      // 先根据当前模块类型筛选题目
      final typeQuestions = allQuestions.where((question) => 
        question.type == widget.questionType
      ).toList();
      
      // 打印当前类型题目的分类，用于调试
      developer.log('_loadCategories 中类型为 ${widget.questionType} 的题目数量: ${typeQuestions.length}');
      for (var question in typeQuestions) {
        developer.log('题目ID: ${question.id}, 类型: "${question.type}", 分类: "${question.category}"');
      }
      
      // 手动提取所有不为空的分类并去重
      final categorySet = <String>{};
      for (var question in typeQuestions) {
        if (question.category.isNotEmpty) {
          categorySet.add(question.category);
        }
      }
      
      final categories = categorySet.toList();
      categories.sort();
      
      // 打印最终的分类列表
      developer.log('最终的分类列表: $categories');
      
      setState(() {
        _categories = categories;
      });
    } catch (e) {
      developer.log('加载分类失败: $e', error: e);
    }
  }
  
  // 加载考点列表
  Future<void> _loadKeyPoints() async {
    try {
      // 获取所有题目
      final allQuestions = await _databaseService.questionRepository.getAllQuestions();
      
      // 先根据当前模块类型筛选题目
      final typeQuestions = allQuestions.where((question) => 
        question.type == widget.questionType
      ).toList();
      
      // 从筛选后的题目中提取考点
      final keyPoints = typeQuestions
          .map((question) => question.keyPoint)
          .where((keyPoint) => keyPoint.isNotEmpty)
          .toSet()
          .toList();
      keyPoints.sort();
      
      // 打印最终的考点列表
      developer.log('类型为 ${widget.questionType} 的考点列表: $keyPoints');
      
      setState(() {
        _keyPoints = keyPoints;
      });
    } catch (e) {
      developer.log('加载考点失败: $e', error: e);
    }
  }
  
  // 搜索变化处理
  void _onSearchChanged() {
    // 保存当前文本
    final currentText = _searchController.text;
    
    // 使用延迟执行，避免每输入一个字符就立即触发搜索
    Future.delayed(const Duration(milliseconds: 300), () {
      // 确保当前文本与延迟前相同，避免快速输入时的频繁刷新
      if (currentText == _searchController.text) {
        setState(() {
          _searchQuery = _searchController.text;
          _applyFilters();
        });
      }
    });
  }
  
  // 应用所有筛选条件
  void _applyFilters() {
    if (_searchQuery.isEmpty && _selectedKeyPoint == null && _selectedCategory == null) {
      // 没有筛选条件
      _filteredQuestions = _questions;
      return;
    }
    
    // 应用搜索、分类和考点筛选
    final query = _searchQuery.toLowerCase();
    _filteredQuestions = _questions.where((question) {
      // 搜索条件
      bool matchesSearch = _searchQuery.isEmpty || 
          question.question.toLowerCase().contains(query) ||
          question.optionA.toLowerCase().contains(query) ||
          question.optionB.toLowerCase().contains(query) ||
          question.optionC.toLowerCase().contains(query) ||
          question.optionD.toLowerCase().contains(query) ||
          question.explanation.toLowerCase().contains(query) ||
          question.keyPoint.toLowerCase().contains(query);
      
      // 分类筛选
      bool matchesCategory = _selectedCategory == null || 
          question.category == _selectedCategory;
      
      // 考点筛选
      bool matchesKeyPoint = _selectedKeyPoint == null || 
          question.keyPoint == _selectedKeyPoint;
      
      return matchesSearch && matchesCategory && matchesKeyPoint;
    }).toList();
  }
  
  // 重置所有筛选条件
  void _resetFilters() {
    setState(() {
      _searchController.clear();
      _selectedKeyPoint = null;
      _selectedCategory = null;
      _filteredQuestions = _questions;
    });
  }
  
  Future<void> _loadQuestions() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });
      
      // 确保数据库已初始化
      await _databaseService.init();
      
      // 获取所有题目
      final allQuestions = await _databaseService.questionRepository.getAllQuestions();
      
      // 根据questionType筛选题目
      final filteredByType = allQuestions.where((question) => 
        question.type == widget.questionType
      ).toList();
      
      // 打印筛选后的题目信息，用于调试
      developer.log('根据type=${widget.questionType}筛选后的题目数量: ${filteredByType.length}');
      for (var question in filteredByType) {
        developer.log('题目ID: ${question.id}, 类型: "${question.type}", 分类: "${question.category}"');
      }
      
      // 设置筛选后的题目列表
      setState(() {
        _questions = filteredByType;
        _applyFilters(); // 应用当前的筛选条件
        _isLoading = false;
      });
      
      // 加载题目后刷新分类列表
      await _loadCategories();
    } catch (e) {
      developer.log('加载题目失败: $e', error: e);
      setState(() {
        _isLoading = false;
        _errorMessage = '加载题目失败: $e';
      });
    }
  }
  
  Future<void> _deleteQuestion(Question question) async {
    try {
      await _databaseService.questionRepository.deleteQuestion(question.id!);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('题目删除成功', style: TextStyle(fontFamily: 'FangSong'))),
      );
      _loadQuestions(); // 重新加载题目列表
    } catch (e) {
      developer.log('删除题目失败: $e', error: e);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('删除题目失败: $e', style: const TextStyle(fontFamily: 'FangSong'))),
      );
    }
  }

  String get questionTypeTitle {
    switch (widget.questionType) {
      case 'politics':
        return '时政题目';
      case 'common_sense':
        return '常识判断';
      case 'verbal_comprehension':
        return '言语理解与表达';
      case 'quantitative_relation':
        return '数量关系';
      case 'logical_reasoning':
        return '判断推理';
      case 'data_analysis':
        return '资料分析';
      default:
        return '题目';
    }
  }

  // 删除确认对话框
  Future<void> _showDeleteConfirmDialog(Question question) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认删除', style: TextStyle(fontFamily: 'FangSong')),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                const Text('确定要删除这道题目吗？', style: TextStyle(fontFamily: 'FangSong')),
                const SizedBox(height: 8.0),
                Text(question.question, style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('删除', style: TextStyle(color: Colors.red, fontFamily: 'FangSong')),
              onPressed: () {
                Navigator.of(context).pop();
                _deleteQuestion(question);
              },
            ),
          ],
        );
      },
    );
  }

  // 直接进入题目导入导出页面
  void _showImportExportDialog() async {
    // 获取要导出的题目列表
    List<Question> questionsToProcess = [];
    
    // 如果是多选模式且有选中的题目，则只传递选中的题目
    if (_isMultiSelectMode && _selectedQuestionIds.isNotEmpty) {
      questionsToProcess = _filteredQuestions.where(
        (question) => question.id != null && _selectedQuestionIds.contains(question.id)
      ).toList();
    } else {
      // 否则传递当前过滤后的所有题目
      questionsToProcess = _filteredQuestions;
    }
    
    // 将题目转换为Map格式
    final List<Map<String, dynamic>> questionsToExport = questionsToProcess.isEmpty 
      ? <Map<String, dynamic>>[] 
      : questionsToProcess.map<Map<String, dynamic>>((question) => <String, dynamic>{
          'type': question.type,
          'category': question.category,
          'point': question.keyPoint,
          'content': question.question,
          'question_image_url': _isValidImagePath(question.questionImageUrl) ? question.questionImageUrl : '',
          'option_a': question.optionA,
          'option_a_image_url': _isValidImagePath(question.optionAImageUrl) ? question.optionAImageUrl : '',
          'option_b': question.optionB,
          'option_b_image_url': _isValidImagePath(question.optionBImageUrl) ? question.optionBImageUrl : '',
          'option_c': question.optionC,
          'option_c_image_url': _isValidImagePath(question.optionCImageUrl) ? question.optionCImageUrl : '',
          'option_d': question.optionD,
          'option_d_image_url': _isValidImagePath(question.optionDImageUrl) ? question.optionDImageUrl : '',
          'correct_answer': question.correctAnswer,
          'explanation': question.explanation,
          'explanation_image_url': _isValidImagePath(question.explanationImageUrl) ? question.explanationImageUrl : '',
        }).toList();
    
    // 导航到QuestionImportExportScreen，并传递当前列表题目
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => QuestionImportExportScreen(initialQuestions: questionsToExport),
      ),
    );
    // 如果返回结果为true，刷新题目列表
    if (result == true) {
      _loadQuestions();
    }
  }

  // 导出当前列表题目
  Future<void> _exportCurrentQuestions() async {
    try {
      // 如果没有题目，显示提示
      if (_filteredQuestions.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('当前列表没有题目可导出', style: TextStyle(fontFamily: 'FangSong'))),
        );
        return;
      }
      
      // 将Question对象转换为Map格式，以符合导出函数的要求
      final questionsToExport = _filteredQuestions.map((question) => {
        'type': question.type,
        'category': question.category,
        'point': question.keyPoint,
        'content': question.question,
        'question_image_url': _isValidImagePath(question.questionImageUrl) ? question.questionImageUrl : '',
        'option_a': question.optionA,
        'option_a_image_url': _isValidImagePath(question.optionAImageUrl) ? question.optionAImageUrl : '',
        'option_b': question.optionB,
        'option_b_image_url': _isValidImagePath(question.optionBImageUrl) ? question.optionBImageUrl : '',
        'option_c': question.optionC,
        'option_c_image_url': _isValidImagePath(question.optionCImageUrl) ? question.optionCImageUrl : '',
        'option_d': question.optionD,
        'option_d_image_url': _isValidImagePath(question.optionDImageUrl) ? question.optionDImageUrl : '',
        'correct_answer': question.correctAnswer,
        'explanation': question.explanation,
        'explanation_image_url': _isValidImagePath(question.explanationImageUrl) ? question.explanationImageUrl : '',
      }).toList();
      
      // 打印每个题目的图片路径，用于调试
      for (var question in _filteredQuestions) {
        if (question.questionImageUrl != null && question.questionImageUrl!.isNotEmpty) {
          developer.log('题目ID: ${question.id}, 图片路径: ${question.questionImageUrl}');
        }
      }
      
      // 确保图片路径正确传递到导出函数
       developer.log('导出题目数量: ${questionsToExport.length}');
       for (var q in questionsToExport) {
         if (q['question_image_url'] != null && q['question_image_url'].toString().isNotEmpty) {
           developer.log('题目图片路径: ${q['question_image_url']}');
         }
       }
      
      // 导出题目
      final filePath = await WordImportExportUtil.exportQuestionsToCSV(questionsToExport);
      
      if (filePath != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('成功导出 ${questionsToExport.length} 道题目到: $filePath', style: const TextStyle(fontFamily: 'FangSong'))),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('导出题目失败', style: TextStyle(fontFamily: 'FangSong'))),
        );
      }
    } catch (e) {
      developer.log('导出题目失败: $e', error: e);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导出题目失败: $e', style: const TextStyle(fontFamily: 'FangSong'))),
      );
    }
  }
  
  // 检查图片路径是否有效
  bool _isValidImagePath(String? imagePath) {
    if (imagePath == null || imagePath.isEmpty) {
      return false;
    }
    
    // 任何非空路径都视为有效，确保所有图片路径都能导出
    return true;
  }
  
  // 导出选中的题目
  Future<void> _exportSelectedQuestions() async {
    try {
      // 如果没有选中题目，显示提示
      if (_selectedQuestionIds.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请先选择要导出的题目', style: TextStyle(fontFamily: 'FangSong'))),
        );
        return;
      }
      
      // 筛选出选中的题目
      final selectedQuestions = _filteredQuestions.where(
        (question) => question.id != null && _selectedQuestionIds.contains(question.id)
      ).toList();
      
      // 将Question对象转换为Map格式，以符合导出函数的要求
      final questionsToExport = selectedQuestions.map((question) => {
        'type': question.type,
        'category': question.category,
        'point': question.keyPoint,
        'content': question.question,
        'question_image_url': _isValidImagePath(question.questionImageUrl) ? question.questionImageUrl : '',
        'option_a': question.optionA,
        'option_a_image_url': _isValidImagePath(question.optionAImageUrl) ? question.optionAImageUrl : '',
        'option_b': question.optionB,
        'option_b_image_url': _isValidImagePath(question.optionBImageUrl) ? question.optionBImageUrl : '',
        'option_c': question.optionC,
        'option_c_image_url': _isValidImagePath(question.optionCImageUrl) ? question.optionCImageUrl : '',
        'option_d': question.optionD,
        'option_d_image_url': _isValidImagePath(question.optionDImageUrl) ? question.optionDImageUrl : '',
        'correct_answer': question.correctAnswer,
        'explanation': question.explanation,
        'explanation_image_url': _isValidImagePath(question.explanationImageUrl) ? question.explanationImageUrl : '',
      }).toList();
      
      // 确保图片路径正确传递到导出函数
       developer.log('导出选中题目数量: ${questionsToExport.length}');
       for (var q in questionsToExport) {
         if (q['question_image_url'] != null && q['question_image_url'].toString().isNotEmpty) {
           developer.log('选中题目图片路径: ${q['question_image_url']}');
         }
       }
      
      // 导出题目
      final filePath = await WordImportExportUtil.exportQuestionsToCSV(questionsToExport);
      
      if (filePath != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('成功导出 ${questionsToExport.length} 道题目到: $filePath')),
        );
        
        // 导出成功后退出多选模式
        setState(() {
          _selectedQuestionIds.clear();
          _isMultiSelectMode = false;
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('导出题目失败')),
        );
      }
    } catch (e) {
      developer.log('导出选中题目失败: $e', error: e);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导出选中题目失败: $e', style: const TextStyle(fontFamily: 'FangSong'))),
      );
    }
  }

  // 批量删除题目
  Future<void> _batchDeleteQuestions() async {
    try {
      // 确认对话框
      final bool? confirm = await showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('确认批量删除', style: TextStyle(fontFamily: 'FangSong')),
            content: Text('确定要删除选中的 ${_selectedQuestionIds.length} 道题目吗？此操作不可撤销。', style: const TextStyle(fontFamily: 'FangSong')),
            actions: <Widget>[
              TextButton(
                child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
              ),
              TextButton(
                child: const Text('删除', style: TextStyle(color: Colors.red, fontFamily: 'FangSong')),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
      
      if (confirm != true) return;
      
      // 执行批量删除
      for (final id in _selectedQuestionIds) {
        await _databaseService.questionRepository.deleteQuestion(id);
      }
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('成功删除 ${_selectedQuestionIds.length} 道题目', style: const TextStyle(fontFamily: 'FangSong'))),
      );
      
      // 清空选择并退出多选模式
      setState(() {
        _selectedQuestionIds.clear();
        _isMultiSelectMode = false;
      });
      
      // 重新加载题目列表
      _loadQuestions();
    } catch (e) {
      developer.log('批量删除题目失败: $e', error: e);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('批量删除题目失败: $e', style: const TextStyle(fontFamily: 'FangSong'))),
      );
    }
  }
  
  // 构建图片显示组件
  Widget _buildImageWidget(String? imagePath) {
    // 如果图片路径为空，则不显示图片
    if (imagePath == null || imagePath.isEmpty) {
      return const SizedBox.shrink();
    }
    
    // 检查是否是本地文件路径
    bool isLocalFilePath = imagePath.startsWith('/') || 
                          RegExp(r'^[A-Za-z]:\\').hasMatch(imagePath) || 
                          imagePath.startsWith('c:/') || 
                          imagePath.startsWith('C:/') ||
                          imagePath.contains(':\\Users\\') ||
                          imagePath.contains(':/Users/') ||
                          imagePath.contains('/Users/') ||
                          imagePath.contains('/Documents/');
    
    if (isLocalFilePath) {
      // 在Web平台上，本地文件路径无法直接访问
      if (kIsWeb) {
        return Container(
          padding: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.orange.shade300),
            borderRadius: BorderRadius.circular(8.0),
            color: Colors.orange.shade50,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.warning_amber_rounded, color: Colors.orange.shade700),
                  const SizedBox(width: 8),
                  Text(
                    '本地图片无法显示',
                    style: TextStyle(color: Colors.orange.shade700, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                '路径: $imagePath',
                style: TextStyle(fontSize: 12, color: Colors.orange.shade700),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 8),
              Text(
                '请使用网络图片URL替代本地文件路径',
                style: TextStyle(fontSize: 12),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        );
      } else {
        // 在非Web平台上，使用File加载本地图片
        return Image.file(
          File(imagePath),
          fit: BoxFit.contain,
          height: 200,
          errorBuilder: (context, error, stackTrace) => Container(
            padding: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.red.shade300),
              borderRadius: BorderRadius.circular(8.0),
              color: Colors.red.shade50,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.error_outline, color: Colors.red.shade700),
                    const SizedBox(width: 8),
                    Text(
                      '图片加载失败',
                      style: TextStyle(color: Colors.red),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  '错误: $error',
                  style: TextStyle(fontSize: 12, color: Colors.red.shade700),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        );
      }
    }
    
    // 使用StatefulBuilder来管理重新加载状态
    return StatefulBuilder(
      builder: (context, setState) {
        bool isReloading = false;
        
        return Container(
          constraints: const BoxConstraints(
            maxHeight: 200, // 限制图片最大高度
          ),
          margin: const EdgeInsets.symmetric(vertical: 8.0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Image.network(
              isReloading ? "$imagePath?reload=${DateTime.now().millisecondsSinceEpoch}" : imagePath,
              fit: BoxFit.contain,
              loadingBuilder: (context, child, loadingProgress) {
                if (loadingProgress == null) return child;
                return Container(
                  height: 100,
                  alignment: Alignment.center,
                  child: const CircularProgressIndicator(),
                );
              },
              errorBuilder: (context, error, stackTrace) {
                // 图片加载失败时显示错误信息和重试按钮
                return Container(
                  padding: const EdgeInsets.all(8.0),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.red.shade300),
                    borderRadius: BorderRadius.circular(8.0),
                    color: Colors.red.shade50,
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.error_outline, color: Colors.red.shade700),
                          const SizedBox(width: 8),
                          Text(
                            '图片加载失败',
                            style: TextStyle(color: Colors.red),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      // 显示错误详情
                      Text(
                        '错误: ${error.toString()}',
                        style: TextStyle(fontSize: 12, color: Colors.red.shade700),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 8),
                      // 重试按钮
                      ElevatedButton.icon(
                        onPressed: () {
                          setState(() {
                            isReloading = true;
                          });
                        },
                        icon: const Icon(Icons.refresh),
                        label: const Text('重试', style: TextStyle(fontFamily: 'FangSong')),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red.shade100,
                          foregroundColor: Colors.red.shade700,
                        ),
                      ),
                    ],
                  ),
                );
              },
              // 图片配置
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isMultiSelectMode 
            ? '已选择 ${_selectedQuestionIds.length} 项' 
            : '${questionTypeTitle}列表',
            style: const TextStyle(fontFamily: 'FangSong')),
        centerTitle: true,
        leading: _isMultiSelectMode 
            ? IconButton(
                icon: const Icon(Icons.close),
                onPressed: () {
                  setState(() {
                    _isMultiSelectMode = false;
                    _selectedQuestionIds.clear();
                  });
                },
              )
            : null,
        actions: [
          // 导入导出按钮
          if (!_isMultiSelectMode) ...[            
            // 导入导出按钮
            IconButton(
              icon: const Icon(Icons.import_export),
              tooltip: '题目导入导出',
              onPressed: _showImportExportDialog,
            ),
          ],
          // 多选模式下的操作
          if (_isMultiSelectMode) ...[            
            // 导入导出按钮
            IconButton(
              icon: const Icon(Icons.import_export),
              tooltip: '题目导入导出',
              onPressed: _showImportExportDialog,
            ),
            // 全选按钮
            IconButton(
              icon: const Icon(Icons.select_all),
              onPressed: () {
                setState(() {
                  if (_selectedQuestionIds.length == _filteredQuestions.length) {
                    // 如果已全选，则取消全选
                    _selectedQuestionIds.clear();
                  } else {
                    // 否则全选
                    _selectedQuestionIds = _filteredQuestions
                        .where((q) => q.id != null)
                        .map((q) => q.id!)
                        .toSet();
                  }
                });
              },
            ),
            // 删除按钮
            IconButton(
              icon: const Icon(Icons.delete),
              onPressed: _selectedQuestionIds.isNotEmpty 
                  ? _batchDeleteQuestions 
                  : null,
            ),
          ] else ...[            
            // 多选按钮
            IconButton(
              icon: const Icon(Icons.select_all),
              onPressed: _filteredQuestions.isNotEmpty 
                  ? () {
                      setState(() {
                        _isMultiSelectMode = true;
                      });
                    }
                  : null,
            ),
            // 筛选按钮
            IconButton(
              icon: const Icon(Icons.filter_list),
              onPressed: _showFilterDialog,
            ),
          ],
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage != null
              ? Center(child: Text(_errorMessage!))
              : _buildQuestionList(),
      floatingActionButton: _isMultiSelectMode 
          ? null 
          : FloatingActionButton(
              onPressed: () async {
                // 使用Navigator.push并等待结果
                final result = await Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => AddEditQuestionScreen(questionType: widget.questionType),
                  ),
                );
                
                // 如果返回结果为true，刷新列表
                if (result == true) {
                  _loadQuestions();
                  _loadKeyPoints(); // 重新加载考点列表
                }
              },
              tooltip: '添加${questionTypeTitle}',
              // 浮动按钮不需要设置文本样式
              child: const Icon(Icons.add),
            ),
    );
  }
  
  // 筛选对话框
  Future<void> _showFilterDialog() async {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('筛选题目', style: TextStyle(fontFamily: 'FangSong')),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('按分类筛选:', style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
                const SizedBox(height: 8.0),
                DropdownButton<String>(
                  isExpanded: true,
                  hint: const Text('选择分类', style: TextStyle(fontFamily: 'FangSong')),
                  value: _selectedCategory,
                  items: [
                    const DropdownMenuItem<String>(
                      value: null,
                      child: Text('全部分类', style: const TextStyle(fontFamily: 'FangSong')),
                    ),
                    ..._categories.map((category) {
                      return DropdownMenuItem<String>(
                        value: category,
                        child: Text(category, style: const TextStyle(fontFamily: 'FangSong')),
                      );
                    }).toList(),
                  ],
                  onChanged: (value) {
                    setState(() {
                      _selectedCategory = value;
                    });
                    Navigator.of(context).pop();
                    _applyFilters();
                  },
                ),
                const SizedBox(height: 16.0),
                const Text('按考点筛选:', style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
                const SizedBox(height: 8.0),
                DropdownButton<String>(
                  isExpanded: true,
                  hint: const Text('选择考点', style: TextStyle(fontFamily: 'FangSong')),
                  value: _selectedKeyPoint,
                  items: [
                    const DropdownMenuItem<String>(
                      value: null,
                      child: Text('全部考点', style: const TextStyle(fontFamily: 'FangSong')),
                    ),
                    ..._keyPoints.map((keyPoint) {
                      return DropdownMenuItem<String>(
                        value: keyPoint,
                        child: Text(keyPoint, style: const TextStyle(fontFamily: 'FangSong')),
                      );
                    }).toList(),
                  ],
                  onChanged: (value) {
                    setState(() {
                      _selectedKeyPoint = value;
                    });
                    Navigator.of(context).pop();
                    _applyFilters();
                  },
                ),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('重置筛选', style: TextStyle(fontFamily: 'FangSong')),
              onPressed: () {
                Navigator.of(context).pop();
                _resetFilters();
              },
            ),
          ],
        );
      },
    );
  }
  
  // 搜索对话框方法已移除，搜索框直接显示在列表顶部
  
  Widget _buildQuestionList() {
    return Column(
      children: [
        // 搜索框
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            controller: _searchController,
            decoration: InputDecoration(
              hintText: '搜索题目、选项或解析...',
              hintStyle: const TextStyle(fontFamily: 'FangSong'),
              prefixIcon: const Icon(Icons.search),
              suffixIcon: _searchQuery.isNotEmpty
                ? IconButton(
                    icon: const Icon(Icons.clear),
                    onPressed: () {
                      _searchController.clear();
                    },
                  )
                : null,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              filled: true,
              fillColor: Colors.grey.shade50,
            ),
            style: const TextStyle(fontFamily: 'FangSong'),
          ),
        ),
        
        // 显示搜索结果数量
        if (_searchQuery.isNotEmpty)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
            child: Text(
              '找到 ${_filteredQuestions.length} 道题目',
              style: const TextStyle(fontFamily: 'FangSong', color: Colors.grey),
            ),
          ),
        
        // 显示筛选状态
        if (_selectedCategory != null || _selectedKeyPoint != null)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (_searchQuery.isNotEmpty)
                        Text(
                          '搜索: "$_searchQuery"',
                          style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                        ),
                      if (_selectedCategory != null)
                        Text(
                          '分类: $_selectedCategory',
                          style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                        ),
                      if (_selectedKeyPoint != null)
                        Text(
                          '考点: $_selectedKeyPoint',
                          style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                        ),
                      Text(
                        '找到 ${_filteredQuestions.length} 个结果',
                        style: const TextStyle(fontSize: 12, fontFamily: 'FangSong'),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: () {
                    setState(() {
                      _resetFilters();
                    });
                  },
                ),
              ],
            ),
          ),
        
        // 题目列表
        Expanded(
          child: _filteredQuestions.isEmpty
            ? _buildEmptyState(context)
            : ListView.builder(
                padding: const EdgeInsets.all(16.0),
                itemCount: _filteredQuestions.length,
                itemBuilder: (context, index) {
                  final question = _filteredQuestions[index];
                  final bool isSelected = question.id != null && _selectedQuestionIds.contains(question.id!);
                  
                  return Card(
                elevation: 2.0,
                margin: const EdgeInsets.only(bottom: 16.0),
                color: isSelected ? Colors.blue.shade50 : null,
                child: InkWell(
                  onTap: _isMultiSelectMode
                      ? () {
                          // 多选模式下点击切换选中状态
                          if (question.id != null) {
                            setState(() {
                              if (isSelected) {
                                _selectedQuestionIds.remove(question.id!);
                              } else {
                                _selectedQuestionIds.add(question.id!);
                              }
                            });
                          }
                        }
                      : null,
                  onLongPress: !_isMultiSelectMode
                      ? () {
                          // 长按进入多选模式
                          setState(() {
                            _isMultiSelectMode = true;
                            if (question.id != null) {
                              _selectedQuestionIds.add(question.id!);
                            }
                          });
                        }
                      : null,
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (_isMultiSelectMode) ...[                              
                              Padding(
                                padding: const EdgeInsets.only(right: 12.0, top: 2.0),
                                child: Icon(
                                  isSelected 
                                      ? Icons.check_circle 
                                      : Icons.circle_outlined,
                                  color: isSelected ? Colors.blue : Colors.grey,
                                ),
                              ),
                            ],
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  // 使用MathFormulaWidget处理题目内容中的分数
                                  MathFormulaWidget(
                                    content: question.question,
                                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                                  ),
                                  // 显示题目图片
                                  if (question.questionImageUrl != null && question.questionImageUrl!.isNotEmpty) ...[  
                                    const SizedBox(height: 8.0),
                                    _buildImageWidget(question.questionImageUrl!),
                                  ],
                                  const SizedBox(height: 8.0),
                                  // 显示分类
                                  if (question.category != null && question.category!.isNotEmpty) ...[  
                                    Text(
                                      '分类: ${question.category}',
                                      style: const TextStyle(color: Colors.blue, fontFamily: 'FangSong'),
                                    ),
                                    const SizedBox(height: 4.0),
                                  ],
                                  // 显示考点
                                  if (question.keyPoint != null && question.keyPoint!.isNotEmpty) ...[  
                                    Text(
                                      '考点: ${question.keyPoint}',
                                      style: const TextStyle(color: Colors.blue, fontFamily: 'FangSong'),
                                    ),
                                    const SizedBox(height: 8.0),
                                  ],
                                  // 选项A
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const Text('A. ', style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            MathFormulaWidget(
                                              content: question.optionA,
                                              style: const TextStyle(fontFamily: 'FangSong'),
                                            ),
                                            if (question.optionAImageUrl != null && question.optionAImageUrl!.isNotEmpty) ...[  
                                              const SizedBox(height: 4.0),
                                              _buildImageWidget(question.optionAImageUrl!),
                                            ],
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  // 选项B
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const Text('B. ', style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            MathFormulaWidget(
                                              content: question.optionB,
                                              style: const TextStyle(fontFamily: 'FangSong'),
                                            ),
                                            if (question.optionBImageUrl != null && question.optionBImageUrl!.isNotEmpty) ...[  
                                              const SizedBox(height: 4.0),
                                              _buildImageWidget(question.optionBImageUrl!),
                                            ],
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  // 选项C
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const Text('C. ', style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            MathFormulaWidget(
                                              content: question.optionC,
                                              style: const TextStyle(fontFamily: 'FangSong'),
                                            ),
                                            if (question.optionCImageUrl != null && question.optionCImageUrl!.isNotEmpty) ...[  
                                              const SizedBox(height: 4.0),
                                              _buildImageWidget(question.optionCImageUrl!),
                                            ],
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  // 选项D
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const Text('D. ', style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            MathFormulaWidget(
                                              content: question.optionD,
                                              style: const TextStyle(fontFamily: 'FangSong'),
                                            ),
                                            if (question.optionDImageUrl != null && question.optionDImageUrl!.isNotEmpty) ...[  
                                              const SizedBox(height: 4.0),
                                              _buildImageWidget(question.optionDImageUrl!),
                                            ],
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 8.0),
                                  Text('正确答案: ${question.correctAnswer}', 
                                    style: const TextStyle(color: Colors.green, fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                                  ),
                                  if (question.explanation.isNotEmpty) ...[  
                                    const SizedBox(height: 8.0),
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        const Text('解析: ', style: TextStyle(color: Colors.blue, fontFamily: 'FangSong')),
                                        Expanded(
                                          child: MathFormulaWidget(
                                            content: question.explanation,
                                            style: const TextStyle(color: Colors.blue, fontFamily: 'FangSong'),
                                          ),
                                        ),
                                      ],
                                    ),
                                    // 显示解析图片
                                    if (question.explanationImageUrl != null && question.explanationImageUrl!.isNotEmpty) ...[  
                                      const SizedBox(height: 4.0),
                                      _buildImageWidget(question.explanationImageUrl!),
                                    ],
                                  ],
                                  if (question.keyPoint.isNotEmpty) ...[  
                                    const SizedBox(height: 8.0),
                                    Text('考点: ${question.keyPoint}', 
                                      style: const TextStyle(color: Colors.purple, fontFamily: 'FangSong'),
                                    ),
                                  ],
                                ],
                              ),
                            ),
                          ],
                        ),
                        if (!_isMultiSelectMode) ...[                          
                          const SizedBox(height: 16.0),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              TextButton.icon(
                                icon: const Icon(Icons.edit),
                                label: const Text('编辑', style: TextStyle(fontFamily: 'FangSong')),
                                onPressed: () async {
                                  // 使用Navigator.push并等待结果
                                  final result = await Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => AddEditQuestionScreen(
                                        questionType: widget.questionType,
                                        questionId: question.id,
                                      ),
                                    ),
                                  );
                                  
                                  // 如果返回结果为true，刷新列表
                                  if (result == true) {
                                    _loadQuestions();
                                    _loadKeyPoints(); // 重新加载考点列表
                                  }
                                },
                              ),
                              const SizedBox(width: 8.0),
                              TextButton.icon(
                                icon: const Icon(Icons.delete, color: Colors.red),
                                label: const Text('删除', style: TextStyle(color: Colors.red, fontFamily: 'FangSong')),
                                onPressed: () => _showDeleteConfirmDialog(question),
                              ),
                            ],
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }
  
  // 此处已删除重复定义的 _getIconForQuestionType 方法
  
  // 注意：此处已有 _showSearchDialog 方法的定义，不需要重复定义
  // 获取题目类型对应的图标
  // 注意：此处已有 _getIconForQuestionType 方法的定义，不需要重复定义
  // 获取题目类型对应的颜色
  // 注意：此处已有 _getColorForQuestionType 方法的定义，不需要重复定义
  
  // 构建空状态显示
  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            _getIconForQuestionType(widget.questionType),
            size: 80,
            color: _getColorForQuestionType(widget.questionType),
          ),
          const SizedBox(height: 20),
          Text(
            '${questionTypeTitle}列表',
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(fontFamily: 'FangSong'),
          ),
          const SizedBox(height: 40),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Text(
              _searchQuery.isNotEmpty
                  ? '没有找到包含"${_searchQuery}"的题目'
                  : _selectedCategory != null || _selectedKeyPoint != null
                      ? '没有找到匹配筛选条件的题目'
                      : '暂无${questionTypeTitle}，点击下方按钮添加题目。',
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 16, fontFamily: 'FangSong'),
            ),
          ),
          if (_searchQuery.isNotEmpty || _selectedCategory != null || _selectedKeyPoint != null) ...[  
            const SizedBox(height: 20),
            ElevatedButton.icon(
              icon: const Icon(Icons.clear_all),
              label: const Text('清除筛选条件', style: TextStyle(fontFamily: 'FangSong')),
              onPressed: () {
                setState(() {
                  _resetFilters();
                });
              },
            ),
          ],
        ],
      ),
    );
  }
  // 删除不完整的代码块
  

  
  // 此处已删除重复定义的 _showSearchDialog 方法
  
  IconData _getIconForQuestionType(String type) {
    switch (type) {
      case 'politics':
        return Icons.account_balance;
      case 'common_sense':
        return Icons.psychology;
      case 'verbal_comprehension':
        return Icons.menu_book;
      case 'quantitative_relation':
        return Icons.calculate;
      case 'logical_reasoning':
        return Icons.quiz;
      case 'data_analysis':
        return Icons.analytics;
      default:
        return Icons.help_outline;
    }
  }
  
  Color _getColorForQuestionType(String type) {
    switch (type) {
      case 'politics':
        return Colors.blue;
      case 'common_sense':
        return Colors.green;
      case 'verbal_comprehension':
        return Colors.orange;
      case 'quantitative_relation':
        return Colors.red;
      case 'logical_reasoning':
        return Colors.purple;
      case 'data_analysis':
        return Colors.teal;
      default:
        return Colors.grey;
    }
  }
  
  // 注意：此处已有 _buildEmptyState 方法的定义，不需要重复定义
  
  // 此处已删除重复定义的 _buildQuestionList 方法
  
}